#!/usr/bin/env bash

### BEGIN ###
# Author: idevz
# Since: 2018/03/12
# Description:       Set up Lua development environment.
# ./init.sh          Set up using $(pwd) as BASE_DIR, down which has lua source and binaries.
#
# Environment variables that control init:
# LV: Lua version which you want to install.
### END ###

set -ex

[ $HOME != '/home/z' ] && echo 'Are U Z ?' && exit 1
H_PROXY_ADDR="http://127.0.0.1:8118"
NO_PROXY="localhost,127.0.0.1,::1,10.211.55.0/16,10.96.0.0/12,10.244.0.0/16"
BASE_DIR=${BASE_DIR:-"$(readlink -f "$(dirname "$0")")"}
OUT_GOING_ACCOUNT_FILE=${OGA:-"out-accounts-info.zj"}
source "${BASE_DIR}/${OUT_GOING_ACCOUNT_FILE}"
PRI_REGISTRY="${OUT_IP}:5000"
NODES=(kube2 kube3)

sudo_write() {
	local content="${1}"
	local file_name="${2}"
	local if_add=
	[ ! -z ${3} ] && if_add="-a"
	echo "${content}" | sudo tee ${if_add} "${file_name}" >/dev/null 2>&1
}

init_out_going() {
	sudo yum -y install python-pip privoxy net-tools
	sudo pip install --upgrade pip
	sudo pip install shadowsocks
	local shadowsocks_conf=
	shadowsocks_conf=$(
		cat <<SS_CONF
{
    "server":"${OUT_IP}",
    "server_port":${OUT_PORT},
    "local_address":"127.0.0.1",
    "local_port":1080,
    "password":"${OUT_PASWD}",
    "timeout":300,
    "method":"aes-256-cfb",
    "fast_open":false
}
SS_CONF
	)
	sudo_write "${shadowsocks_conf}" "/etc/shadowsocks.json"

	local whitelist_conf=
	whitelist_conf=$(
		cat <<WT_CONF
{{alias}}
# 代理(socks5)
socks5 = +forward-override{forward-socks5 127.0.0.1:1080 .}
# 直连
direct = +forward-override{forward .}

# 所有网站走代理
{socks5}
/

# 以下网站走直连
{direct}
.ip.cn
WT_CONF
	)
	sudo_write "${whitelist_conf}" "/etc/privoxy/whitelist.action"
	sudo_write 'actionsfile whitelist.action' "/etc/privoxy/config" true

	local out_profile=
	out_profile=$(
		cat <<OUT_PROFILE
alias unstart_out="unset ALL_PROXY HTTP_PROXY HTTPS_PROXY all_proxy http_proxy https_proxy"
alias reload_out="sudo systemctl restart out_going.service && sudo systemctl restart privoxy.service"

proxy="${H_PROXY_ADDR}"
export ALL_PROXY=\${proxy}
export HTTP_PROXY=\${proxy}
export HTTPS_PROXY=\${proxy}
export all_proxy=\${proxy}
export http_proxy=\${proxy}
export https_proxy=\${proxy}
export NO_PROXY="${NO_PROXY}"
OUT_PROFILE
	)
	sudo_write "${out_profile}" "/etc/profile" true
	source /etc/profile

	sudo_write "proxy=${H_PROXY_ADDR}" /etc/yum.conf true

	local out_service_unit=
	out_service_unit=$(
		cat <<OUT_SERVICE
[Unit]
Description=Out Going Service
After=network.target

[Service]
ExecStart=/bin/sslocal \
	    -c /etc/shadowsocks.json \
	    /dev/null 2>&1
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure
KillMode=process

[Install]
WantedBy=multi-user.target
OUT_SERVICE
	)
	sudo_write "${out_service_unit}" '/lib/systemd/system/out_going.service'
	sudo systemctl enable out_going
	sudo systemctl start out_going
	sudo systemctl start privoxy.service
	# systemctl -l status privoxy.service
}

init_docker() {
	sudo yum install -y docker
	local docker_service_unit=
	docker_service_unit=$(
		cat <<DOCKER_SERVICE
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.com
After=network.target
Wants=docker-storage-setup.service
Requires=docker-cleanup.timer

[Service]
Type=notify
NotifyAccess=all
EnvironmentFile=-/run/containers/registries.conf
EnvironmentFile=-/etc/sysconfig/docker
EnvironmentFile=-/etc/sysconfig/docker-storage
EnvironmentFile=-/etc/sysconfig/docker-network
Environment=GOTRACEBACK=crash
Environment=DOCKER_HTTP_HOST_COMPAT=1
Environment=PATH=/usr/libexec/docker:/usr/bin:/usr/sbin
Environment="HTTP_PROXY=${H_PROXY_ADDR}" "NO_PROXY=${NO_PROXY}"
ExecStartPost=/usr/sbin/iptables -P FORWARD ACCEPT
ExecStart=/usr/bin/dockerd-current \
          --add-registry=${PRI_REGISTRY} \
          --insecure-registry=${PRI_REGISTRY} \
          --add-runtime docker-runc=/usr/libexec/docker/docker-runc-current \
          --default-runtime=docker-runc \
          --exec-opt native.cgroupdriver=systemd \
          --userland-proxy-path=/usr/libexec/docker/docker-proxy-current \
          $OPTIONS \
          $DOCKER_STORAGE_OPTIONS \
          $DOCKER_NETWORK_OPTIONS \
          $ADD_REGISTRY \
          $BLOCK_REGISTRY \
          $INSECURE_REGISTRY	  $REGISTRIES
ExecReload=/bin/kill -s HUP $MAINPID
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=0
Restart=on-abnormal
MountFlags=slave
KillMode=process

[Install]
WantedBy=multi-user.target
DOCKER_SERVICE
	)
	sudo_write "${docker_service_unit}" "/lib/systemd/system/docker.service"
	local docker_daemon_json=
	docker_daemon_json=$(
		cat <<DDJ
		{ "insecure-registries":["${PRI_REGISTRY}"] }
DDJ
	)
	sudo_write "${docker_daemon_json}" "/etc/docker/daemon.json"
	[ ! -f "/usr/libexec/docker/docker-runc" ] &&
		sudo ln -s "/usr/libexec/docker/docker-runc-current" "/usr/libexec/docker/docker-runc"
	sudo systemctl enable docker &&
		sudo systemctl start docker
}

update_docker() {
	# sudo yum remove -y 'docker*'
	sudo yum install -y yum-utils \
		device-mapper-persistent-data \
		lvm2
	sudo yum-config-manager \
		--add-repo \
		https://download.docker.com/linux/centos/docker-ce.repo
	sudo yum-config-manager --enable docker-ce-edge
	sudo yum-config-manager --enable docker-ce-test
	# sudo yum-config-manager --disable docker-ce-edge
	sudo yum install -y docker-ce-18.06.1.ce
	local docker_service_unit=
	docker_service_unit=$(
		cat <<DOCKER_SERVICE
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd \
          --insecure-registry=${PRI_REGISTRY} \
		  --registry-mirror=http://${PRI_REGISTRY}
ExecReload=/bin/kill -s HUP $MAINPID
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
# Uncomment TasksMax if your systemd version supports it.
# Only systemd 226 and above support this version.
#TasksMax=infinity
TimeoutStartSec=0
# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes
# kill only the docker process, not all processes in the cgroup
KillMode=process
# restart the docker process if it exits prematurely
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[Install]
WantedBy=multi-user.target
DOCKER_SERVICE
	)
	sudo_write "${docker_service_unit}" "/lib/systemd/system/docker.service"
	sudo mkdir "/etc/docker"
	local docker_daemon_json=
	docker_daemon_json=$(
		cat <<EOF
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "50m"
  },
  "storage-driver": "overlay2",
  "storage-opts": [
    "overlay2.override_kernel_check=true"
  ]
}
EOF
	)
	sudo_write "${docker_daemon_json}" "/etc/docker/daemon.json"
	sudo mkdir -p /etc/systemd/system/docker.service.d
	sudo systemctl daemon-reload
	sudo systemctl start docker
	sudo systemctl enable docker
}

preper_kubeadm() {
	KUBE_YUM=$(
		cat <<KUBE_Y
[kubernetes]
name=Kubernetes
baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=1
gpgkey=https://packages.cloud.google.com/yum/doc/yum-key.gpg https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg
exclude=kube*
KUBE_Y
	)
	sudo_write "${KUBE_YUM}" "/etc/yum.repos.d/kubernetes.repo"

	# Set SELinux in permissive mode (effectively disabling it)
	sudo setenforce 0
	sudo sed -i 's/^SELINUX=enforcing$/SELINUX=Disabled/' /etc/selinux/config

	sudo yum install -y kubelet kubeadm kubectl --disableexcludes=kubernetes

	sudo systemctl enable kubelet && sudo systemctl start kubelet

	KUBE_SYSCTL_CONF=$(
		cat <<KUBE_S
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
KUBE_S
	)
	sudo_write "${KUBE_SYSCTL_CONF}" /etc/sysctl.d/k8s.conf
	sudo sysctl --system
}

init_kubeadm() {
	sudo swapoff -a #KUBELET_EXTRA_ARGS="--fail-swap-on=false"

	for kube_image in $(kubeadm config images list); do
		local private_kube_image="${PRI_REGISTRY}/${kube_image}"
		sudo docker pull "${private_kube_image}"
		sudo docker tag "${private_kube_image}" "${kube_image}"
	done

	local join=
	if [ ${HOSTNAME} = 'kube1' ]; then
		sudo kubeadm init --config $RUN_PATH/kubeadm.yaml >$RUN_PATH/init.out
		join=$(tail -10 $RUN_PATH/init.out | grep 'kubeadm join')
		join_sh=$(
			cat <<JOIN_SH
#!/usr/bin/env bash

### BEGIN ###
# Author: idevz
# Since: 2018/03/12
# Description:       AUTO Generate by runX.
# ./join.sh          Make a node join to a K8S cluster.
### END ###
sudo ${join}
JOIN_SH
		)
		for node in ${NODES}; do
			[ ! -d "$RUN_PATH/../${node}" ] && mkdir -p "$RUN_PATH/../${node}"
			echo "${join_sh}" >$RUN_PATH/../${node}/join.sh
			chmod +x $RUN_PATH/../${node}/join.sh
		done
	else
		sudo $RUN_PATH/join.sh
	fi
}

init() {
	sudo systemctl stop firewalld &&
		sudo systemctl disable firewalld
	init_out_going
	update_docker
	preper_kubeadm
	init_kubeadm
}
